package com.example.sample;

import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.example.sample.activity.ForegroundTestActivity;
import com.example.sample.logic.LogImpl;

import net.liteheaven.XbApp;
import net.liteheaven.xblib.common.log.Log4jManager;
import net.liteheaven.xblib.common.log.XLog;
import net.liteheaven.xblib.common.ui.ToastUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_WIFI;

public class SampleApp extends Application {

	private static String TAG = "Application";
	private static SampleApp mInst;
	
	@Override
	public void onCreate() {
		super.onCreate();
		mInst = this;
		performOnAppCreated();
	}
	
	public static SampleApp getApp(){
		return mInst;
	}
	
	private void performOnAppCreated(){
		XbApp.getInstance().setContext(this);

		// 请求root权限
        //PermissionUtil.upgradeRootPermission(getPackageCodePath());

		testWriteFile();

		testNetwork();

 		// 文件日志
		LogImpl.init("/sdcard/xblibdemo", Log.DEBUG);
		LogImpl.i("SampleApp", "onCreate");

		// 崩溃时写文件
		final Thread.UncaughtExceptionHandler h = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				Log.e(ForegroundTestActivity.TAG, "程序崩溃");
				LogImpl.oSync(Log.ERROR, "crash", "程序崩溃", e);
				h.uncaughtException(t, e);
			}
		});
	}
	
	@Override
	protected void attachBaseContext(Context base) {

		// 禁用所有Toast
		//super.attachBaseContext(new CustomContext(base));

		super.attachBaseContext(base);
	}

	public static class CustomContext extends ContextWrapper {
		public CustomContext(Context context){
			super(context);
		}
		@Override
		public Object getSystemService(String name) {
			XLog.i(TAG, "getSystemService " + name);
			if (name != null && name.equals(Context.WINDOW_SERVICE)){
				final WindowManager windowManager = (WindowManager)super.getSystemService(name);
				WindowManager newWindowManager = new WindowManager() {
					@Override
					public Display getDefaultDisplay() {
						return windowManager.getDefaultDisplay();
					}

					@Override
					public void removeViewImmediate(View view) {
						windowManager.removeViewImmediate(view);
					}

					@Override
					public void addView(View view, ViewGroup.LayoutParams params) {
						WindowManager.LayoutParams wm = (WindowManager.LayoutParams)params;
						XLog.i(TAG, "addView type=" + wm.type);
						if (wm.type == WindowManager.LayoutParams.TYPE_TOAST){
							Context ctx = SampleApp.getApp().getApplicationContext();
							XLog.e(TAG, "此Activity不允许显示Toast");
						}else{
							windowManager.addView(view, params);
						}
					}

					@Override
					public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
						WindowManager.LayoutParams wm = (WindowManager.LayoutParams)params;
						if (wm.type == WindowManager.LayoutParams.TYPE_TOAST){

						}else{
							windowManager.updateViewLayout(view, params);
						}
					}

					@Override
					public void removeView(View view) {
						try{
							windowManager.removeView(view);
						}catch(Exception e){
						}
					}
				};
				return newWindowManager;
			}else{
				return super.getSystemService(name);
			}
		}
	}

	private void testWriteFile(){
		ToastUtil.show(this, "这是在OnCreate中弹出的Toast！");
	}

	private void testNetwork(){
		String ip = getIp(this);
		ToastUtil.show(this, ip);
		System.out.println("ip -> " + ip);
	}

	public static String getIp(final Context context) {
		String ip = null;

		NetworkInfo ni = ((ConnectivityManager) XbApp.getInstance().getContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

		if (ni == null){
			ip = "";
		} else if (ni.getType() == TYPE_MOBILE) {
			ip = getLocalIpAddress();
		} else if (ni.getType() == TYPE_WIFI) {
			//获取wifi服务
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			//判断wifi是否开启
			if (!wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(true);
			}
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			int ipAddress = wifiInfo.getIpAddress();
			ip =(ipAddress & 0xFF ) + "." +
					((ipAddress >> 8 ) & 0xFF) + "." +
					((ipAddress >> 16 ) & 0xFF) + "." +
					( ipAddress >> 24 & 0xFF) ;
		}
		return ip;

	}

	/**
	 *
	 * @return 手机GPRS网络的IP
	 */
	private static String getLocalIpAddress()
	{
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {//获取IPv4的IP地址
						return inetAddress.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
		}


		return null;
	}
}
